<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();


if(!CModule::IncludeModule("iblock"))
{
    ShowError("Модуль Информационных блоков не установлен");
    return;
}

if (!$USER->IsAuthorized())
{
    ShowError("Вы должны авторизоваться, чтобы иметь возможность просматривать данный раздел.");
    return;        
}

if (!(CSite::InGroup(array($arParams["GROUP_ADMINS"]))||CSite::InGroup(array($arParams["GROUP_PERFORMERS"]))))
{
    ShowError("У Вас нет доступа к статистике.");
    return;        
}
    
if(!isset($arParams["CACHE_TIME"]))
	$arParams["CACHE_TIME"] = 3600;

$arParams["IBLOCK_TYPE"] = trim($arParams["IBLOCK_TYPE"]);
if(strlen($arParams["IBLOCK_TYPE"])<=0)
 	$arParams["IBLOCK_TYPE"] = "itrequests";
if($arParams["IBLOCK_TYPE"]=="-")
	$arParams["IBLOCK_TYPE"] = "";


$uid = $USER->GetID();
$isAdmin = CSite::InGroup(array($arParams["GROUP_ADMINS"]));
$isPerformer = CSite::InGroup(array($arParams["GROUP_PERFORMERS"]));

if (!($isAdmin || $isPerformer))
{
    ShowError("У Вас нет доступа к статистике.");
    return;        
}



// **************** фильтр ***********************
$FILTER_NAME = $arParams["MAIL_TEMPL_PREFIX"]."_FILTER_STAT";
$arFilterFields = Array("find_date1_DAYS_TO_BACK","find_date1","find_date2");

// Работа с фильтрами
//Delete filter
if (strlen($_REQUEST["del_filter"])>0)
{
    unset($_SESSION["SESS_ADMIN"][$FILTER_NAME]);

    foreach ($arFilterFields as $field)
        $_REQUEST[$field] = "";
}
//Set filter
elseif (strlen($_REQUEST["set_filter"])>0)
{
    $arFilter = Array();
    foreach ($arFilterFields as $field)
        $arFilter[$field] = $_REQUEST[$field];

    $_SESSION["SESS_ADMIN"][$FILTER_NAME] = $arFilter;
    $_SESSION["SESS_ADMIN"][$FILTER_NAME."_USING"] = true;
}
//Get Filter
else
{
    $arFilter = $_SESSION["SESS_ADMIN"][$FILTER_NAME];
    if (is_array($arFilter))
    {
        foreach ($arFilter as $field => $value)
            $_REQUEST[$field] = $value;
    }
}

$find_date1_DAYS_TO_BACK = $_REQUEST["find_date1_DAYS_TO_BACK"];
$find_date1 = $_REQUEST["find_date1"];
$find_date2 = $_REQUEST["find_date2"];

// ***************************************

if($this->StartResultCache(false, array($uid,$FILTER_NAME,$find_date1_DAYS_TO_BACK,$find_date1,$find_date2)))
{   
    $arResult=array(
        "HANDBOOKS" => array(),
        "PERFORMERS" => array(),
        "DATA" => array(),
        "FILTER_NAME" => $FILTER_NAME,
        "FILTER_DAYS_TO_BACK" => $find_date1_DAYS_TO_BACK,
        "FILTER_FIND_DATE1" => $find_date1,
        "FILTER_FIND_DATE2" => $find_date2,
        "FILTER_ERROR" => ""
    );

    //// ***** выбираем справочники ***** ////
    
    // ответственные
    $performers = array();
    $filter = Array("GROUPS_ID" => Array($arParams["GROUP_PERFORMERS"], $arParams["GROUP_ADMINS"]));
    $rsUsers = CUser::GetList(($by="last_name"), ($order="asc"), $filter);         
    while ($user = $rsUsers->GetNext())
    {
        $arResult["PERFORMERS"][] = $user;
    }
           
    // категории
    $arSelect = Array(
        "ID",
        "NAME",
        "PROPERTY_DEFAULT_RESPONSIBLE"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CATEGORY"],
        "ACTIVE" => "Y",
    );
    $arSort = array("SORT"=>"ASC");
        
    $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
    while($arItem = $rsElement->GetNext())
    {
        $arResult["HANDBOOKS"]["CATEGORY"][] = $arItem;            
    }        

    if ($arParams["USE_PROJECT"]=="Y")
    {
        // проекты
        $arSelect = Array(
            "ID",
            "NAME"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_PROJECT"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");

        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            $arResult["HANDBOOKS"]["PROJECT"][] = $arItem;            
        }       
    }
    
    // статусы
    $arSelect = Array(
        "ID",
        "NAME"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_STATUSES"],
        "ACTIVE" => "Y",
    );
    $arSort = array("SORT"=>"ASC");
        
    $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
    while($arItem = $rsElement->GetNext())
    {
        $arResult["HANDBOOKS"]["STATUSES"][] = $arItem;            
    }       
    
    // критичность
    $arSelect = Array(
        "ID",
        "NAME"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CRITICALITY"],
        "ACTIVE" => "Y",
    );
    $arSort = array("SORT"=>"ASC");

    $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
    while($arItem = $rsElement->GetNext())
    {
        $arResult["HANDBOOKS"]["CRITICALITY"][] = $arItem;            
    }  
    
    // оценки ответов
    $arSelect = Array(
        "ID",
        "NAME"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_MARK"],
        "ACTIVE" => "Y",
    );
    $arSort = array("SORT"=>"ASC");

    $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
    while($arItem = $rsElement->GetNext())
    {
        $arResult["HANDBOOKS"]["MARK"][] = $arItem;            
    }       
    
    //// ***** заполняем данные ***** ////
    
    // выбираем свойства инфоблока для определения типа комментария
     $types = array();
     $prs = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$arParams["IBLOCK_REQUESTS_LOGS_ID"], "CODE"=>"TYPE"));
     while($field = $prs->GetNext())
     {
         $types[$field["VALUE"]] = $field["ID"];
     } 

    // выбираем заявки
    $arSelect = Array(
        "ID",
        "PROPERTY_CATEGORY",
        "PROPERTY_STATUS",
        "PROPERTY_RESPONSIBLE_USER",
        "PROPERTY_CRITICALITY",
        "PROPERTY_PROJECT",
        "PROPERTY_MARK",        
        "PROPERTY_DATE_CLOSE",
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_ID"],
        "ACTIVE" => "Y",
    );

    // если установлен фильтр, то добавляем даты в выборку заявок
    if ($arResult["FILTER_DAYS_TO_BACK"])
    {
        $date = new DateTime('today');
        $date->sub(new DateInterval('P'.$arResult["FILTER_DAYS_TO_BACK"].'D'));
        $arResult["FILTER_FIND_DATE1"] = $date->format('d.m.Y');
    }
    
    if (strlen($arResult["FILTER_FIND_DATE2"]))
        $arFilter["<="."DATE_CREATE"] = $arResult["FILTER_FIND_DATE2"];
    
    if (strlen($arResult["FILTER_FIND_DATE1"]))
        $arFilter[">="."DATE_CREATE"] = $arResult["FILTER_FIND_DATE1"];
    
    if (strlen($arResult["FILTER_FIND_DATE1"]) && strlen($arResult["FILTER_FIND_DATE2"]))
    {
        $date1 = new DateTime($arResult["FILTER_FIND_DATE1"]);
        $date2 = new DateTime($arResult["FILTER_FIND_DATE2"]);
        if ($date2 < $date1)
            $arResult["FILTER_ERROR"] = 'В фильтре дата "по" должна быть больше чем дата "с"';
    }
            
    $items = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect);
    while ($item = $items->GetNext())
    {         
        if (strlen($item["PROPERTY_DATE_CLOSE_VALUE"]))
        {
            $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["closed"]++;
            $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["all"]++;
            $arResult["DATA"]["responsibility"]["all"]["closed"]++;
            $arResult["DATA"]["responsibility"]["all"]["all"]++;

            $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["closed"]++;
            $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["all"]++;

            $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["closed"]++;
            $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["all"]++;

            $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["closed"]++;
            $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["all"]++;

            $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["closed"]++;
            $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["all"]++;
            
            $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["closed"]++;
            $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["all"]++;            
        }
        else 
        {
                
            $arSelect = Array(
                "ID",
                "DATE_CREATE",
                "CREATED_BY",
            );

            $arFilter = array(
                "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_LOGS_ID"],
                "ACTIVE" => "Y",
                "PROPERTY_REQUEST" => $item["ID"],
                "!PROPERTY_TYPE" => array($types["Системная"], $types["Комментарий скрытый"])
            );

            $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);        
            if ($elem = $rsElement->GetNext())
            {
                $cid = CUser::GetUserGroup($elem["CREATED_BY"]);
                if (in_array($arParams["GROUP_PERFORMERS"], $cid)||in_array($arParams["GROUP_ADMINS"], $cid))
                {
                    $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["green"]++;
                    $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["open"]++;
                    $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["all"]++;
                    $arResult["DATA"]["responsibility"]["all"]["green"]++;
                    $arResult["DATA"]["responsibility"]["all"]["open"]++;
                    $arResult["DATA"]["responsibility"]["all"]["all"]++;

                    $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["green"]++;
                    $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["open"]++;
                    $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["all"]++;

                    $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["green"]++;
                    $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["open"]++;
                    $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["all"]++;

                    $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["green"]++;
                    $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["open"]++;
                    $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["all"]++;

                    $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["green"]++;
                    $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["open"]++;
                    $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["all"]++; 
                    
                    $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["green"]++;
                    $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["open"]++;
                    $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["all"]++;                        
                    
                }
                else
                if (in_array($arParams["GROUP_CLIENTS"], $cid))
                {
                    $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["red"]++;
                    $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["open"]++;
                    $arResult["DATA"]["responsibility"][$item["PROPERTY_RESPONSIBLE_USER_VALUE"]]["all"]++;
                    $arResult["DATA"]["responsibility"]["all"]["red"]++;
                    $arResult["DATA"]["responsibility"]["all"]["open"]++;
                    $arResult["DATA"]["responsibility"]["all"]["all"]++;

                    $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["red"]++;
                    $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["open"]++;
                    $arResult["DATA"]["category"][$item["PROPERTY_CATEGORY_VALUE"]]["all"]++;

                    $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["red"]++;
                    $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["open"]++;
                    $arResult["DATA"]["project"][$item["PROPERTY_PROJECT_VALUE"]]["all"]++;

                    $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["red"]++;
                    $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["open"]++;
                    $arResult["DATA"]["status"][$item["PROPERTY_STATUS_VALUE"]]["all"]++;

                    $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["red"]++;
                    $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["open"]++;
                    $arResult["DATA"]["criticality"][$item["PROPERTY_CRITICALITY_VALUE"]]["all"]++;
                    
                    $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["red"]++;
                    $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["open"]++;
                    $arResult["DATA"]["mark"][$item["PROPERTY_MARK_VALUE"]]["all"]++;                    
                }
            }
        }
    }
    
    $this->IncludeComponentTemplate();
    
    
}

//echo "<pre>";
//print_r($arResult);
//echo "</pre>";

$APPLICATION->AddChainItem("Статистика");
?>


